﻿// Copyright 2013 Ronald Schlenker, www.technewlogic.de.
// 
// This file is part of Byond.
// 
// Byond is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 2 of the License, or
// (at your option) any later version.
// 
// Byond is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
// 
// You should have received a copy of the GNU General Public License
// along with Byond.  If not, see <http://www.gnu.org/licenses/>.

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using NLog;
using Newtonsoft.Json;

namespace Byond
{
	public class SettingsManager
	{
		private readonly Env _env;
		private readonly List<object> _settingsStore = new List<object>();
		private readonly JsonSerializerSettings _jsonSerializerSettings;
		private readonly Logger _logger;

		public SettingsManager()
		{
			_jsonSerializerSettings = new JsonSerializerSettings
			{
				TypeNameHandling = TypeNameHandling.All
			};
		}

		private void Ctor()
		{
			var settingsPath = GetSettingsPath();
			if (!File.Exists(settingsPath))
				return;

			var json = File.ReadAllText(settingsPath);
			try
			{
				var settings = JsonConvert.DeserializeObject(json, _jsonSerializerSettings) as List<object>;
				if (settings != null)
					_settingsStore.AddRange(settings);
			}
			catch (Exception e)
			{
				_logger.Error("Could not deserialize default settings", e);
			}
		}

		public T TryGetSettings<T>() where T : class
		{
			return _settingsStore.FirstOrDefault(it => it.GetType() == typeof(T)) as T;
		}

		public void UpdateSettings<T>(T settingsObject) where T : class
		{
			var oldSettings = TryGetSettings<T>();
			if (oldSettings != null)
				_settingsStore.Remove(oldSettings);
			_settingsStore.Add(settingsObject);

			PersistSettings();
		}

		private void PersistSettings()
		{
			var json = JsonConvert.SerializeObject(_settingsStore, _jsonSerializerSettings);
			File.WriteAllText(GetSettingsPath(), json);
		}

		private string GetSettingsPath()
		{
			return _env.RootPath + "\\Settings.dat";
		}
	}
}
